package drds.global_transaction.common.util;

public class Json
{
	private static String getLevelString(int level)
	{
		StringBuilder sb = new StringBuilder();
		for (int index = 0; index < level; index++)
		{
			sb.append("\t");
		}
		return sb.toString();
	}

	public static String formate(String jsonString)
	{
		int level = 0;
		// 存放格式化的json字符串
		StringBuilder sb = new StringBuilder();
		for (int index = 0; index < jsonString.length(); index++)// 将字符串中的字符逐个按行输出
		{
			// 获取s中的每个字符
			char charAt = jsonString.charAt(index);
			// level大于0并且jsonForMatStr中的最后一个字符为\n,jsonForMatStr加入\t
			if (level > 0 && '\n' == sb.charAt(sb.length() - 1))
			{
				sb.append(getLevelString(level));
			}
			// 遇到"{"和"["要增加空格和换行，遇到"}"和"]"要减少空格，以对应，遇到","要换行
			switch (charAt)
			{
			case '{':
			case '[':
				sb.append(charAt + "\n");
				level++;
				break;
			case ',':
				sb.append(charAt + "\n");
				break;
			case '}':
			case ']':
				sb.append("\n");
				level--;
				sb.append(getLevelString(level));
				sb.append(charAt);
				break;
			default:
				sb.append(charAt);
				break;
			}
		}
		return sb.toString();

	}

}